<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 字典操作类 itemHandler
 * @package  htdocs
 * @subpackage  module/base
 * @author   allen.qiang
 * @version 1.0
 */
 
class itemHandler {
	
	//数据库实例
	private $dbca;
	
	function __construct(  &$dbca ) {
		$this->dbca = $dbca;
	}


    /**
     * 查询字典表信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'itemID' => int 字典id
            'itemCategoryID' => int 分类id
            'useFlg' => int 使用标志
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchItem( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //id
        if (isset($arg_array['itemID']) && is_numeric($arg_array['itemID'])) {
            $sql .= ' AND itemID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['itemID'];
        }

        //分类id
        if (isset($arg_array['itemName']) && !empty($arg_array['itemName'])) {
            $sql .= ' AND itemName LIKE ?';
            $params_type .= 's';
            $params_array[] = "%".$arg_array['itemName']."%";
        }
        
        //分类id
        if (isset($arg_array['itemCategoryID']) && is_numeric($arg_array['itemCategoryID'])) {
            $sql .= ' AND itemCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['itemCategoryID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }


        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM sys_item ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM sys_item ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'itemID' => $item->itemID,
                    'itemName' => $item->itemName,
                    'itemCategoryID' => $item->itemCategoryID,
                    'useFlg' => $item->useFlg,
                    'extend_1' => $item->extend_1,
                    'extend_2' => $item->extend_2,
                    'extend_3' => $item->extend_3,
                    'extend_4' => $item->extend_4,
                    'extend_5' => $item->extend_5,
                    'extend_6' => $item->extend_6,
                    'extend_7' => $item->extend_7,
                    'extend_8' => $item->extend_8
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


	
	/**
	 * 查询字典分类信息
	 *
	 * @param int $categoryID 分类ID
	 */
	function getItemCategory ( $categoryID = '' ) {
		
		if(!empty($categoryID)){
			if(!is_numeric($categoryID)){
				return array( 'code' => 400, 'message' => '分类参数有误' );
			}
		}
		
		if( is_numeric($categoryID)){
			$string = 'SELECT uuid,timeStamp,creator,createTime,editor,itemCategoryID,itemCategoryName,memo,itemlist_tpl,item_tpl 
				   FROM sys_itemcategory WHERE itemCategoryID=?';
			$category_array = $this->dbca->stmt_query($string, 'i', $categoryID);
		}else{
			$string = 'SELECT uuid,timeStamp,creator,createTime,editor,itemCategoryID,itemCategoryName,memo,itemlist_tpl,item_tpl 
				   FROM sys_itemcategory';
			$category_array = $this->dbca->stmt_query($string);	
		}
		if(!$category_array){
			return false;
		}else{
			return $category_array;
		}
		
	}
	
	/**
	 * 查询字典信息
	 *
	 * @param int $itemID 字典ID
	 */
	function getItemInfo ( $itemID = '' ) {
		
		if(!empty($itemID)){
			if(!is_numeric($itemID)){
				return array( 'code' => 400, 'message' => '字典参数有误' );
			}
		}
		
		if(is_numeric($itemID)){
			$string = 'SELECT editor,createTime,creator,itemID,itemCategoryID,itemName,sortorder,useFlg,extend_1,extend_2,extend_3,
				       extend_4,extend_5,extend_6,extend_7,extend_8 FROM sys_item WHERE itemID=?';
			$item_array = $this->dbca->stmt_query($string, 'i', $itemID);
		}else{
			$string = 'SELECT editor,createTime,creator,itemID,itemCategoryID,itemName,sortorder,useFlg,extend_1,extend_2,extend_3,
				       extend_4,extend_5,extend_6,extend_7,extend_8 FROM sys_item';
			$item_array = $this->dbca->stmt_query($string);
		}
		
		if($item_array){
			return $item_array;
		}else{
			return false;
		}
		
		
	}
		
	/**
	 * 保存字典信息
	 *
	 * @param array           $item_array         				 字典保存信息数组
	 * @param smallint(5)     $item_array['item_category_ID']  	 分类ID 
	 * @param mediumint(8)    $item_array['$itemID']    		 字典ID
	 * @param varchar(100)    $item_array['itemName'] 		     字典名
	 * @param varchar(200)    $item_array['extend_1']  			 扩展1
	 * @param varchar(200)    $item_array['extend_2']   		 扩展2
	 * @param datetime        $item_array['extend_3']    		 扩展3
	 * @param datetime    	  $item_array['extend_4']    		 扩展4
	 * @param int    		  $item_array['extend_5']  			 扩展5
	 * @param int    		  $item_array['extend_6']    		 扩展6
	 * @param decimal(8,2)    $item_array['extend_7']    		 扩展7
	 * @param decimal(8,2)    $item_array['extend_8']  			 扩展8
	 * @return unknown
	 * 
	 */
	function itemSave( $item_array ){
	
	//实例化公共类	
	$commHandler = new commHandler();	
		
	 $extend_1 = !isset($item_array['extend_1']) ? null : $item_array['extend_1']; 
	 $extend_2 = !isset($item_array['extend_2']) ? null : $item_array['extend_2']; 
	 $extend_3 = !isset($item_array['extend_3']) ? null : $item_array['extend_3']; 
	 $extend_4 = !isset($item_array['extend_4']) ? null : $item_array['extend_4']; 
	 $extend_5 = !isset($item_array['extend_5']) ? null : $item_array['extend_5']; 
	 $extend_6 = !isset($item_array['extend_6']) ? null : $item_array['extend_6']; 
	 $extend_7 = !isset($item_array['extend_7']) ? null : $item_array['extend_7']; 
	 $extend_8 = !isset($item_array['extend_8']) ? null : $item_array['extend_8'];
	 $useFlg = !isset($item_array['useFlg']) ? null : $item_array['useFlg'];          
	 $sortorder = !isset($item_array['sortorder']) ? null : $item_array['sortorder'];
	 
	 if (!isset($item_array['itemName']) || empty($item_array['itemName']))
		 return array( 'code' => 400, 'message' => '名称不能为空' );
	 
	 if (!isset($item_array['item_category_ID']) || !is_numeric($item_array['item_category_ID']))
		return array( 'code' => 400, 'message' => '分类参数有误' );
	 
	if(!isset($item_array['itemID'])){
		$itemID = '';
	}else{
		
		if(!is_numeric($item_array['itemID']))
			return array( 'code' => 400, 'message' => '字典参数有误' );
		
		$itemID = $item_array['itemID'];
	}	
		
	 $item_category_ID = $item_array['item_category_ID'];
	 $itemName = $item_array['itemName'];
	 
	 	
	 	//查询字典分类信息
	 	$category_array = $this->getItemCategory( $item_category_ID );
	 	if (!$category_array)
	 		return array( 'code' => 404, 'message' => '没有找到该分类信息' );
	 	
	 	$item = new entity('sys_item');
	 	if (!empty($itemID)) {
	 		
	 		$item->itemID = $itemID;
	 		
	 		if(!$this->dbca->fetch($item)) 
	 			return array( 'code' => 404, 'message' => '没有找到该字典信息' );
	 	} 
	 	
	 	$item->itemName = $itemName;
	 	$item->itemCategoryID = $item_category_ID;
	 	$item->sortorder = $sortorder;
	 	$item->useFlg = $useFlg;
	    $item->extend_1 = $extend_1;
	    $item->extend_2 = $extend_2;
	 	$item->extend_3 = $extend_3;
	 	$item->extend_4 = $extend_4;
	 	$item->extend_5 = $extend_5;
	 	$item->extend_6 = $extend_6;
	 	$item->extend_7 = $extend_7;
	 	$item->extend_8 = $extend_8;
	
	 	$this->dbca->save($item, 'backend');
		
	 	if($itemID){
	 		return array( 'code' => 200, 'message' => '已更新' );
	 	}else{
	 		return array( 'code' => 200, 'message' => '已保存' );
	 	}
	 	
	}
	
	/**
	 * array $params 查询参数数组
	 * 查询字典表信息
	 */
	function itemSearch( $params ){
		
			//sql字符串
			$sql = '';
			
			//参数类型字符串
			$params_type = '';
			
			//参数值数组
			$params_array = array();
			
			//分页
			if (isset($params['pageIndex']) && is_numeric($params['pageIndex']) && $params['pageIndex'] > 0)
				$pageIndex = $params['pageIndex'];
			else
				$pageIndex = 1;
			
			//每页显示数量
			if (isset($params['limit']) && is_numeric($params['limit']) && $params['limit'] > 0)
				$limit = $params['limit'];
			else
				$limit = 15;
			
			//按某一字段排序（默认timeStamp）	
			if(isset($params['sortBy']) && !empty($params['sortBy'])){
				$sortBy = $params['sortBy'];
			}else{
				$sortBy = 'timeStamp';
			}
			
			//排序方式（默认DESC）	
			if(isset($params['sortOrder']) && !empty($params['sortOrder'])){
				$sortOrder = $params['sortOrder'];
			}else{
				$sortOrder = 'DESC';
			}
			
			if(isset($params['itemID']) && is_numeric($params['itemID'])){
				$sql .= ' AND itemID = ?';		
				$params_type .= 'i';
				$params_array[] = $params['itemID'];
					
			}
			
			if(isset($params['item_category_ID']) && is_numeric($params['item_category_ID'])){
				$sql .= ' AND itemCategoryID = ?';		
				$params_type .= 'i';
				$params_array[] = $params['item_category_ID'];
					
			}
			
			if( !empty($params['itemName'])){
				
				$sql .= ' AND itemName = ?';		
				$params_type .= 's';
				$params_array[] = $params['itemName'];
					
			}
			
			if( !empty($params['extend_1'])){
				
				$sql .= ' AND extend_1 = ?';		
				$params_type .= 's';
				$params_array[] = $params['extend_1'];
					
			}
		
			if( !empty($params['extend_2'])){
				
				$sql .= ' AND extend_2 = ?';		
				$params_type .= 's';
				$params_array[] = $params['extend_2'];
					
			}
			
			if( !empty($params['extend_3'])){
				
				$sql .= ' AND extend_3 = ?';		
				$params_type .= 's';
				$params_array[] = $params['extend_3'];
					
			}
			
			if( !empty($params['extend_4'])){
				
				$sql .= ' AND extend_4 = ?';	
				$params_type .= 's';
				$params_array[] = $params['extend_4'];
					
			}
			
			if( !empty($params['extend_5'])){
				
				$sql .= ' AND extend_5 = ?';		
				$params_type .= 'i';
				$params_array[] = $params['extend_5'];
					
			}
			
			if( !empty($params['extend_6'])){
				
				$sql .= ' AND extend_6 = ?';		
				$params_type .= 'i';
				$params_array[] = $params['extend_6'];
					
			}
			
			if( !empty($params['extend_7'])){
				
				$sql .= ' AND extend_7 = ?';		
				$params_type .= 'i';
				$params_array[] = $params['extend_7'];
					
			}
			
			if( !empty($params['extend_8'])){
				
				$sql .= ' AND extend_8 = ?';		
				$params_type .= 'i';
				$params_array[] = $params['extend_8'];
					
			}
			
			if ($sql) {
				$sql = ' WHERE ' . substr($sql, 4);
			}
			
			//统计数目
			$sql_count = 'SELECT COUNT(*) num FROM sys_item' . $sql;
			$result_count = $this->dbca->stmt_query($sql_count,$params_type,$params_array);
			$listCount = $result_count[0]->num;
			
			if($listCount == 0){
				return array( 'code' => 404, 'message' => '查询到0条信息' );
			}
			
			//查询结果
			$sql .= ' ORDER BY ' . $sortBy .' ' .$sortOrder . ' LIMIT '.($pageIndex - 1) * $limit . ','. $limit;
			$sql_search = 'SELECT editor,createTime,creator,itemID,itemCategoryID,itemName,sortorder,useFlg,extend_1,extend_2,extend_3,
				               extend_4,extend_5,extend_6,extend_7,extend_8 
				               FROM sys_item' .$sql;
			
			$result_query = $this->dbca->stmt_query($sql_search,$params_type,$params_array);
	
			return array('code'=>200,'listCount'=>$listCount,'search'=>$result_query);
		
	}
	
	/**
	 * int $itemID 字典ID
	 * 字典表信息的禁用、启用
	 */
	function itemChange($itemID){
		
		if(!isset($itemID) || !is_numeric($itemID) || empty($itemID)){
			return array('code'=>400,'message'=>'参数错误，请与管理员联系');
		}
		
		$item_change = new entity('sys_item');
		$item_change->itemID = $itemID;
		if(!$this->dbca->fetch($item_change)){
			return array('code'=>404,'message'=>'没有找到该字典相关的信息');
		}
		$flg = $item_change->useFlg;
		if($item_change->useFlg == 1){
	 		$item_change->useFlg = 0;
	 	}else{
	 		$item_change->useFlg = 1;
	 	}
	 	$item_change->itemName = $item_change->itemName;
		$this->dbca->save($item_change, 'backend');
		
	 	if($flg == 1){
	 		return array('code'=>200,'message'=>'已禁用');
	 	}else{
	 		return array('code'=>200,'message'=>'已启用');
	 	}
	 	
	 	
	}
	/**
	 * 根据条件查询字典信息
	 * @author raohenglei
	 * @param array $arg_array 参数数组
	 * @param return
	 */
	public function searchItemList ( &$arg_array ) {
		
		//sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        
        //分类ID
		if (isset($arg_array['item']) && is_numeric($arg_array['item'])) {
			$sql .= ' AND itemCategoryID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['item'];
		} else {
			return array('code' => 400, 'message' => '参数错误，请联系系统管理员');
		}
        
		//编号
		if (isset($arg_array['itemID']) && is_numeric($arg_array['itemID'])) {
			$sql .= ' AND itemID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['itemID'];
		}
        
		//名称
		if (isset($arg_array['itemName']) && !empty($arg_array['itemName'])) {
			$sql .= ' AND itemName = ?';
			$params_type .= 's';
			$params_array[] = $arg_array['itemName'];
 		}
		
		if ($sql) {
			$sql = 'WHERE ' . substr($sql, 4);
		}
         
         try {
			  if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {
				
				    //统计分类数量
				    $search_sql = 'SELECT COUNT(*) AS item_count FROM sys_item ' . $sql;
				    $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				    $item_count = $count_array[0]->item_count;
				    if ($item_count == 0) {
				        $arg_array['count'] = 0;
				        return null;
				    }
				
				    $arg_array['count'] = $item_count;
				
				    //排序
				    if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				        $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
				
				    //分页
				    if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				        $arg_array['page'] = 1;
				
				    $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
				
				} else {
				
				    $arg_array['count'] = 0;
				
				    //排序
				    if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				        $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
				
				}

            //查询分类信息
            $search_sql = 'SELECT * FROM sys_item ' . $sql;;
            $item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            return $item_array;
         } catch (Exception $e) {
         	error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );
         }
	}
	
	/**
     * 删除字典表信息
     *
     * @param array $arg_array
     * @return array
     */
    public function deleteItem( $arg_array ) {

        if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        if (empty($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '请选择要删除的资源位' );

        $delete_array = explode('_', $arg_array['delete_str']);

        try {

            foreach($delete_array as &$itemID) {

                if (!is_numeric($itemID))
                    return array( 'code' => 400, 'message' => '参数错误' );

                //查询资源位信息
                $item_obj = new entity('sys_item');
                $item_obj->itemID = $itemID;
                if ($this->dbca->fetch($item_obj)) {
                    $this->dbca->delete($item_obj);
                }

            }

            return array( 'code' => 200, 'message' => '删除成功' );

        } catch (Exception $e) {

            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );

        }

    }
}